package com.example.news.apapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.news.R;
import com.example.news.entity.News;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.MyHolder> {

    List<News.ResultDTO.DataDTO> list = new ArrayList<>();
    private Context context;
    private OnItemClickListener onItemClickListener;
    public NewsAdapter(Context context) {
        this.context = context;
    }

    public void setList(List<News.ResultDTO.DataDTO> list) {
        this.list = list;
        // 一定要调用
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        // 加载布局
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_list_item, null);
        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder holder, int position) {
        // 绑定数据
        News.ResultDTO.DataDTO dataDTO = list.get(position);
        holder.title.setText(dataDTO.getTitle());
        holder.authorName.setText(dataDTO.getAuthorName());
        holder.date.setText(dataDTO.getDate());

        // 加䵧图片
        Glide.with(context).load(dataDTO.getThumbnailPicS()).error(R.drawable.ic_menu_camera).into(holder.thumbnailPic);
        holder.itemView.setOnClickListener(x->{
            if (Objects.nonNull(onItemClickListener)) {
                onItemClickListener.onItemClick(dataDTO, position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class MyHolder extends RecyclerView.ViewHolder {
        private ImageView thumbnailPic;
        private TextView title;
        private TextView authorName;
        private TextView date;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            thumbnailPic = itemView.findViewById(R.id.thumbnailPic);
            title = itemView.findViewById(R.id.title);
            authorName = itemView.findViewById(R.id.authorName);
            date = itemView.findViewById(R.id.date);

        }
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface  OnItemClickListener{
        void onItemClick(News.ResultDTO.DataDTO dataDTO, int position);
    }
}
